#!/bin/bash

crashPid=$1
savePath="$2$1/"

uuid=$(cat /proc/sys/kernel/random/uuid)

mkdir -p ${savePath}

# 信息 和 core 文件名
infoFilePath=${savePath}_${crashPid}_${uuid}
coreFilePath=${savePath}_${crashPid}_${uuid}_core

# 获取 coredumpctl 崩溃信息
getSystemdCoredumpInfo()
{
    echo "call getSystemCoredumpInfo"

    # 暂不生成 core 文件
    # coredumpctl dump ${crashPid} -o ${coreFilePath} > ${infoFilePath}
    # if [ -f ${coreFilePath} ] ; then
    #     xz -z ${coreFilePath}
    # fi

    coredumpctl info ${crashPid} > ${infoFilePath}
}

# 获取系统架构
getSystemArch()
{
    echo "call getSystemArch"

    arch=$(arch)
    echo "System Arch: ${arch}" >> ${infoFilePath}
}

# 获取报名及包的依赖
getPkgInfo()
{
    echo "call getPkgInfo"

    # 获取二进制路径
    binPath=$(coredumpctl list -r | grep "${crashPid}" | head -1 | awk -F ' ' '{print $NF}')

    if [ -z "${binPath}" ] ; then
        echo "binPath is empty"
        return
    fi

    # 获取包名
    pkgName=$(dpkg -S "${binPath}" | awk -F ':' '{print $1}')

    # 获取包版本
    pkgVersion=$(dpkg -l | grep "${pkgName}" | awk -F ' ' '{print $3}')

    # 获取包依赖
    pkgDepend=$(apt-cache depends "${pkgName}")

    echo "Package Name: ${pkgName}(${pkgVersion})" >> "${infoFilePath}"
    echo "Package Depend:" >> "${infoFilePath}"
    echo "${pkgDepend}" >> "${infoFilePath}"
}

getSystemdCoredumpInfo
getSystemArch
getPkgInfo
